import operator
import time
from contextlib import contextmanager

import redis
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from constant import constant


# 比较运算符字典
operators = {
    '==': operator.eq,
    '=': operator.eq,
    '>': operator.gt,
    '<': operator.lt,
    '>=': operator.ge,
    '<=': operator.le
}

engine = create_engine(constant.DATABASE_SERVER_URI)
# 创建DBSession类型:
Session = sessionmaker(bind=engine)
pool = redis.ConnectionPool(host=constant.REDIS_HOST, port=constant.REDIS_PORT, password=constant.REDIS_PASSWORD,
                                 decode_responses=True)
r = redis.Redis(connection_pool=pool)

@contextmanager
def my_session():
    session = Session()
    try:
        yield session
        session.commit()
    except Exception as err:
        session.rollback()
        raise
    finally:
        session.close()


@contextmanager
def server_status():
    exception = None
    try:
        yield exception
        # 插入成功计数
        success_count = r.hget(constant.SERVER_STATUS_TABLE, constant.REDIS_SUCCESSCOUNT)
        if not success_count:
            success_count = 1
        else:
            success_count = eval(success_count) + 1
        # 设置数据最新刷新时间
        stime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        # 设置当前服务状态
        status = 'OK'
        r.hmset(constant.SERVER_STATUS_TABLE,{
            constant.REDIS_SUCCESSCOUNT : str(success_count),
            constant.REDIS_LASTREFRESHTIME : str(stime),
            constant.REDIS_ALIVESATUS : status
                 })
    except Exception as err:
        constant.logger.error(err)
        # 设置当前服务状态
        server_status = 'ERROR'
        # 插入失败计数
        fail_count = r.hget(constant.SERVER_STATUS_TABLE, constant.REDIS_FAILCOUNT)
        if not fail_count:
            fail_count = 1
        else:
            fail_count += 1
        r.hmset(constant.SERVER_STATUS_TABLE, {
            constant.REDIS_ALIVESATUS : server_status,
            constant.REDIS_FAILCOUNT : fail_count
        })
    finally:
        pass